﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Linq;
using System.Text;
namespace LunchRoller.Repositories
{
    public class XmlRepository<TValue> : FileRepository<TValue>
    {

        public XmlRepository(string fileName )
            : base( fileName)
        { 
        }
        //public override IAsyncResult BeginSaveAll(AsyncCallback callback, object AsyncState)
        //{
        //    throw new NotImplementedException();
        //}

        //public override IAsyncResult EndSaveAll(IAsyncResult asyncResult)
        //{
        //    throw new NotImplementedException();
        //}



        static DataContractSerializer xml = new DataContractSerializer(typeof(TValue[]));
        protected override void InitData(Stream stream)
        {

            var ms = new MemoryStream();
            stream.CopyTo(ms);
            ms.Seek(0, SeekOrigin.Begin);
            var str = new StreamReader   (ms).ReadToEnd();
            ms.Seek(0, SeekOrigin.Begin);
            var array = (TValue[])xml.ReadObject(ms);
            array
                .Reverse().Take(50).Reverse()
                .ToList().ForEach(i => this.Add(i));
        }

        protected override void WriteAllToStream(Stream stream)
        {
            xml.WriteObject(stream, this.ToArray());
        }
    }
}
